<?php

use app\common\library\AddressParse;
use app\common\model\OrderReceiptModel;

if (!function_exists('_disposeAddress')) {
    function _disposeAddress(string $address=null, string $op=null)
    {
        if (!$address) return ['flag' => 0, 'msg' => '地址核查中'];

        $checkOutArr = $orderArr = $exiKeyArr = array();
        $addressStr = '';
        $address = str_replace('，', ',', $address);
        $addArr = explode(PHP_EOL, $address);
        $exiNum = 0;

        foreach ($addArr as $key => $item) {
            if (empty($item)) {
                unset($addArr[$key]);
                continue;
            }
            if ($op === 'manual') {
                $addressStr .= $item.PHP_EOL;
            } else {
                $itemArr = explode(',', $item);
                if (count($itemArr) !== 4) {
                    unset($addArr[$key]);
                    continue;
                }
                // 状态值不清
                // 0'待付款', 1'已发货', 2'待退款', 3'已退款', 4'驳回退款', 5'交易成功'
                $exists = OrderReceiptModel::where('obtain_order_no', $itemArr[0])->where('order_status', 'not in', '1,2,4,5')->count();
                if ($exists) {
                    array_push($exiKeyArr, $key+1);
                    unset($addArr[$key]);
                    $exiNum ++;
                    continue;
                } else {
                    // array_push($checkOutArr, [$itemArr[0],$itemArr[2],$itemArr[3]]);// 模板
                    array_push($checkOutArr, [$itemArr[0],$itemArr[1],$itemArr[2]]);// 手动
                }
                // $addressStr .= $itemArr[1].PHP_EOL;
                $addressStr .= $itemArr[3].PHP_EOL;
            }
        }
        if ($op === 'manual') {
            return _address_kuaibao_manual($addressStr);
        }
        if (count($addArr) < 1) return ['flag' => 0, 'msg' => '“订单号,地址,姓名,电话”格式错误或订单号全部重复'];

        $data = Db::name('option')->where('option_name', 'cmf_settings')->find();
        $option = json_decode($data['option_value'], true);
        $parseType = $option['addressparse'];
        if ($parseType === 'kuaibao') {
            return _address_kuaibao($addressStr, $checkOutArr, $exiNum, $exiKeyArr);
        } else if ($parseType === 'local') {
            return _address_local($addressStr, $checkOutArr, $exiNum, $exiKeyArr);
        }
    }
}

if (!function_exists('_checkCity')) {
    function _checkCity(array $array)
    {
        if (!is_array($array)) return $array;
        foreach ($array as &$item) {
            if ((strpos($item['city'], '嘉峪关') !== false) ||
                (strpos($item['city'], '三亚') !== false) ||
                (strpos($item['city'], '中山') !== false) ||
                (strpos($item['city'], '东莞') !== false)
            ) {
                if ((strpos($item['city'], '嘉峪关') !== false) && empty($item['area'])) {
                    $item['area'] = '嘉峪关市';
                }
                if ((strpos($item['city'], '三亚') !== false) && empty($item['area'])) {
                    $item['area'] = '崖州区';
                }
                if ((strpos($item['city'], '中山') !== false) && empty($item['area'])) {
                    $item['area'] = '中山市';
                }
                if ((strpos($item['city'], '东莞') !== false) && empty($item['area'])) {
                    $item['area'] = '东莞市';
                }
            }
        }
        return $array;
    }
}

if (!function_exists('_address_kuaibao_manual')) {
    function _address_kuaibao_manual(string $addressStr)
    {
        $addressStr = htmlspecialchars_decode($addressStr);
        $apiHost = "https://open.kuaidihelp.com/Demo/DemoHandle/run";
        $postData = array('type' => 'address');
        $requestData = array(
            'data' => array(
                'text' => $addressStr,
                'is_parse' => 1,
                'resolveTown' => false,
                'multimode' => true
            )
        );
        $postData['request_data'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
        $user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiHost);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.Rand_IP(), 'CLIENT-IP:'.Rand_IP()));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT,300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        $ret = curl_exec($ch);
        curl_close($ch);
        $ret = json_decode(substr($ret, 3), true);
        if ($ret && $ret['code'] == 0) {
            $ret = $ret['data'];
            $res = [];
            foreach ($ret as $key => $item) {
                $arr = array(
                    'province' => $item['province_name'] ?? '',
                    'city' => $item['city_name'] ?? '',
                    'area' => $item['county_name'] ?? '',
                    'town' => $item['town_name'] ?? 'kb',
                    'detail' => $item['detail'] ?? '',
                    'phone' => $item['mobile'] ?? '',
                    'name' => $item['name'] ?? '',
                    'order' => $item['note'] ?? ''
                );
                array_push($res, $arr);
            }
            return ['flag' => 1, 'msg' => '地址解析成功', 'data' => $res];
        } else {
            return ['flag' => 0, 'msg' => $ret['msg'] ?? '地址解析失败'];
        }
    }
}

if (!function_exists('_address_local')) {
    function _address_local(string $addressStr, array $checkOutArr, int $exiNum, array $exiKeyArr)
    {
        if ($exiNum) {
            $exiKeyArr = implode('、', $exiKeyArr);
            $succMsg = "解析成功，检测到第{$exiKeyArr}条订单号重复，已过滤({$exiNum})条";
        }
        $parse = new AddressParse();
        $address = explode(PHP_EOL, $addressStr);
        $res = [];
        foreach ($address as $key => $val) {
            if (!$val) {
                unset($address[$key]);
                continue;
            }
            $data = $parse->setType(1)->parse($val);
            $arr = array(
                'province' => $data['province'] ?? '',
                'city' => $data['city'] ?? '',
                'area' => $data['area'] ?? '',
                'town' => 'lo',
                'detail' => $data['detail'] ?? '',
            );

            $arr['order'] = $checkOutArr[$key][0];
            $arr['name'] = $checkOutArr[$key][1];
            $arr['phone'] = $checkOutArr[$key][2];
            array_push($res, $arr);
        }
        $res = _checkCity($res);
        return ['flag' => 1, 'msg' => $succMsg ?? '地址解析成功', 'data' => $res];
    }
}

if (!function_exists('_address_kuaibao')) {
    function _address_kuaibao(string $addressStr, array $checkOutArr, int $exiNum, array $exiKeyArr=[])
    {
        if ($exiNum) {
            $exiKeyArr = implode('、', $exiKeyArr);
            $succMsg = "解析成功，检测到第{$exiKeyArr}条订单号重复，已过滤({$exiNum})条";
        }
        $addressStr = htmlspecialchars_decode($addressStr);
        $apiHost = "https://open.kuaidihelp.com/Demo/DemoHandle/run";
        $postData = array('type' => 'address');
        $requestData = array(
            'data' => array(
                'text' => $addressStr,
                'is_parse' => 1,
                'resolveTown' => false,
                'multimode' => true
            )
        );
        $postData['request_data'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
        $user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiHost);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.Rand_IP(), 'CLIENT-IP:'.Rand_IP()));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT,300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        $ret = curl_exec($ch);
        curl_close($ch);
        $ret = json_decode(substr($ret, 3), true);
        if ($ret && $ret['code'] == 0) {
            $ret = $ret['data'];
            $res = [];
            foreach ($ret as $key => $item) {
                $arr = array(
                    'province' => $item['province_name'] ?? '',
                    'city' => $item['city_name'] ?? '',
                    'area' => $item['county_name'] ?? '',
                    'town' => $item['town_name'] ?? 'kb',
                    'detail' => $item['detail'] ?? '',
                );
                $arr['order'] = $checkOutArr[$key][0];
                $arr['name'] = $checkOutArr[$key][1];
                $arr['phone'] = $checkOutArr[$key][2];
                array_push($res, $arr);
            }
            return ['flag' => 1, 'msg' => $succMsg ?? '地址解析成功', 'data' => $res];
        } else {
            return ['flag' => 0, 'msg' => $ret['msg'] ?? '地址解析失败'];
        }
    }
}

if (!function_exists('Rand_IP')) {
    function Rand_IP()
    {
        $ip2id= round(rand(600000, 2550000) / 10000);
        $ip3id= round(rand(600000, 2550000) / 10000);
        $ip4id= round(rand(600000, 2550000) / 10000);
        $arr_1 = array("218","218","66","66","218","218","60","60","202","204","66","66","66","59","61","60","222","221","66","59","60","60","66","218","218","62","63","64","66","66","122","211");
        $randarr= mt_rand(0,count($arr_1)-1);
        $ip1id = $arr_1[$randarr];
        return $ip1id.".".$ip2id.".".$ip3id.".".$ip4id;
    }
}

function curlPost($api, $postdata)
{
    $url = "http://yuncangapi.maer.pro" . $api;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT,300);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

if (!function_exists('sendSms')) {
    function sendSms($mobile, $code, $event='register')
    {
        $u = \think\Db::name('cloud_user')->where('id', 1)->find();
        if ($u['logstate'] != 1) return ['code' => 0, 'msg' => '未查询到云仓账户，请联系管理'];
        $api = '/service/sms/send';
        $args = array(
            'token' => $u['token'],
            'mobile' => $mobile,
            'code' => $code,
            'op' => 1,
            'event' => $event
        );
        $ret = json_decode(curlPost($api, $args), true);
        return $ret;
    }
}
